package com.hunantv.mglive.utils;

import android.util.Log;

import com.hunantv.mglive.common.Constant;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.data.common.EncodeData;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.PublicKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by admin on 2015/12/14.
 */
public class MgEncodUtil {
    public static final String TAG = "MgEncodUtil";

    /**
     * 芒果密码加密
     * @param encodeStr
     * @return
     */
    public static String encode(String encodeStr)
    {
        try {
            InputStream inPublic = MaxApplication.getAppContext().getResources().getAssets().open(Constant.RSA_FILE_NAME);
            PublicKey publicKey = RSAUtils.loadPublicKey(inPublic);
            byte[] encryptByte = RSAUtils.encryptData(encodeStr.getBytes(), publicKey);
            return Base64Utils.encode(encryptByte);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /***
     * MD5加密 生成32位md5码
     *
     * @return 返回32位md5码
     */
    public static String md5Encode(String value) throws Exception {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
//        md5.update(key.getBytes());
        byte[] byteArray = value.getBytes("UTF-8");
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**
     * 按照芒果要求封装Header
     * @param param param
     * @return heander
     */
    public static EncodeData getEncodeHeader(Map<String, String> param,String signFill0) {
        EncodeData data = null;
        long salt = 1;
        try {
            long startTime = System.currentTimeMillis();
            while(true){
                long time = System.currentTimeMillis();
                String encode = md5Encode(getValue(param) + time + salt);
                if(encode.startsWith(signFill0)){
                    data = new EncodeData(encode,String.valueOf(time),String.valueOf(salt));
                    break;
                }
                else if(time - startTime > 1000 * 10){
                    //超时保护
                    L.d(TAG,"加密超时");
                    L.d(TAG,"salt="+ salt);
                    L.d(TAG,"start time="+ startTime);
                    L.d(TAG,"end time="+ time);
                    break;
                }
                salt+=1;
            }
            if(data != null)
            {
                L.d(TAG,"encode="+data.getEncode());
                L.d(TAG,"time="+ data.getTime());
                L.d(TAG,"salt="+ data.getSalt());
                L.d(TAG,"耗时="+(System.currentTimeMillis() - startTime));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 按照芒果要求封装Header
     * old,2.0.8.20版本后使用新的
     * @param param param
     * @return heander
     */
    public static Map<String, String> getHeader(Map<String, String> param) {
        String sign = "";
        try {
            sign = MgEncodUtil.md5Encode(getValue(param) + Constant.APP_KEY + getTimeKey());
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i("JUNE", "getRequest sign=" + sign);
        Map<String, String> header = new HashMap<>();
        header.put(Constant.REQEUST_HEADER, sign.toUpperCase());
        return header;
    }

    private static String getValue(Map<String, String> param) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> m : param.entrySet()) {
            sb.append(m.getValue());
        }
        return sb.toString();
    }

    /**
     * 获取当前的是时间Key
     *
     * @return time
     */
    public static int getTimeKey() {
        int timeKey;
//        int timeKey=（当前小时*60*60+当前分钟*60+当前秒）/120    (忽略小数位)
        Date mDate = new Date();
        timeKey = (mDate.getHours() * 3600 + mDate.getMinutes() * 60 + mDate.getSeconds()) / 120;
        return timeKey;
    }
}
